<template>
    <div class="grid-container">
        <div class="page-bread">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/outstorage_action/picking' }">受注出库</el-breadcrumb-item>
                <el-breadcrumb-item>批量出库</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="detail-content">
            <el-tabs activeName="detail">
                <el-tab-pane label="受注出库单" name="detail">
                    <el-table :data="orders" v-loading.body="loading" stripe style="width: 100%">
                        <el-table-column prop="OrderNo" label="受注编号" min-width="200">
                        </el-table-column>
                        <el-table-column prop="OutStcNo" label="出库编号" min-width="200">
                        </el-table-column>
                        <el-table-column prop="FineFlg" label="出库库位代码" min-width="200">
                        </el-table-column>
                        <el-table-column prop="ShopSignNM" label="商店" min-width="200">
                        </el-table-column>
                        <el-table-column prop="DeliverAdd" label="送货地" min-width="200">
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="detail-content">
            <div class="btn-box">
                <el-button type="primary" @click="doChange">确认出库</el-button>
            </div>

            <el-tabs activeName="table">
                <el-tab-pane label="商品明细" name="table">
                    <div class="statistic-content">
                        <p>
                            统计：
                            <span>产品种类：{{ products.length }}</span>
                        </p>
                    </div>
                    <el-table :data="products" v-loading.body="loading" @selection-change="handleSelectionChange" stripe style="width: 100%">

                        <el-table-column type="selection" width="55" :selectable="isSelectable">
                        </el-table-column>
                        <el-table-column prop="CompanyShortNm" label="公司" min-width="200">
                        </el-table-column>
                        <el-table-column prop="PRODCHINM" label="产品中文名称" min-width="300">
                        </el-table-column>
                        <el-table-column prop="PRODENGNM" label="产品英文名称" min-width="300">
                        </el-table-column>
                        <el-table-column prop="ProductAvail" label="商品有效期（月）" min-width="150">
                        </el-table-column>
                        <el-table-column prop="OrderAvail" label="订货有效期（月）" min-width="150">
                        </el-table-column>
                        <el-table-column prop="total" label="受注数量" min-width="150">
                        </el-table-column>
                        <el-table-column prop="outTotal" label="已出库数量" min-width="150">
                        </el-table-column>
                        <el-table-column label="库区选择" min-width="100">
                            <template slot-scope="scope">
                                <div class="action-column">
                                    <el-button type="text" size="small" @click.native.prevent="handleChoose(scope.row)">库区</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- dialog -->
                    <el-dialog title="库区选择" :visible.sync="dialogVisible" width="50%" :modal-append-to-body="false">

                        <el-select v-model="tmpWarehouse" placeholder="请选择仓库" class="warehouse-select" @change="handleWarehouseChange">
                            <el-option v-for="warehouse in wareHouseList" :key="warehouse.id" :label="warehouse.warehouse_name" :value="warehouse.id"> </el-option>
                        </el-select>

                        <span class="warehouse-select">剩余分配数量：{{ resetNum }}</span>

                        <el-table :data="tmpGoods" stripe style="width: 100%">
                            <el-table-column prop="product.PRODCHINM" label="商品名" min-width="150">
                            </el-table-column>
                            <el-table-column prop="location.stock_no" label="库区" min-width="150">
                            </el-table-column>
                            <el-table-column prop="attribute.state_name" label="状态" min-width="150">
                            </el-table-column>
                            <el-table-column prop="CHARG" label="批次号" min-width="150">
                            </el-table-column>
                            <el-table-column prop="number" label="数量" min-width="150">
                            </el-table-column>
                            <el-table-column label="出库数量" min-width="150">
                                <template slot-scope="scope">
                                    <div class="table-form-item">
                                        <el-input v-model.number="scope.row.actNumber" @keyup.native.prevent="inputKeyup($event,scope.row)" size="mini" placeholder="（需填写数值）">
                                        </el-input>
                                        <span class="error-text" v-if="scope.row.errText!=''">{{scope.row.errText}}</span>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>

                        <span slot="footer" class="dialog-footer">
                            <el-button @click="dialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="handleSubStock">确 定</el-button>
                        </span>
                    </el-dialog>

                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script>
import { getByNos, getStockById, stockOut } from '@/api/picking'
import { getAll } from '@/api/warehourse'

export default {
  data() {
    return {
      loading: true,
      dialogVisible: false,
      orders: [],
      products: [],
      wareHouseList: [],
      ids: [],
      checkedGoods: [],
      tmpWarehouse: undefined,
      tmpGoodsRow: {},
      tmpGoods: []
    }
  },
  created() {
    this.ids = this.$route.query
    this.loadOrders(this.ids)
    this.loadWarehouse()
  },
  computed: {
    resetNum() {
      let tmp = this.tmpGoodsRow.total - this.tmpGoodsRow.outTotal
      if (tmp > 0) {
        for (let i = 0; i < this.tmpGoods.length; i++) {
          if (this.tmpGoods[i].actNumber) tmp -= this.tmpGoods[i].actNumber
        }
        return tmp
      }
      return 0
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.checkedGoods = val
    },
    resetTmp() {
      this.tmpWarehouse = undefined
      this.tmpGoods = []
    },
    loadOrders(ids) {
      this.loading = true
      getByNos({ ids: ids })
        .then(res => {
          this.orders = res.data.orders
          this.products = res.data.products
          for (let i = 0; i < this.products.length; i++) {
            this.products[i].stocks = []
          }
          setTimeout(() => {
            this.loading = false
          }, 100)
        })
        .catch(error => {
          this.$router.push({
            path: '/outstorage_action/picking'
          })
        })
    },
    loadWarehouse() {
      getAll().then(res => {
        this.wareHouseList = res.data
      })
    },
    inputKeyup(event, rows) {
      if (!/^\+?[0-9]*$/.test(rows.actNumber)) {
        rows.errText = '请输入不小于零的整数'
        rows.actNumber = ''
      } else if (rows.number < rows.actNumber) {
        rows.errText = '数量不能超过库区实际数量'
        rows.actNumber = ''
      } else {
        rows.errText = ''
        rows.actNumber = event.target.value
      }
    },
    handleWarehouseChange() {
      if (!this.tmpWarehouse) return
      getStockById({
        product_id: this.tmpGoodsRow.id,
        warehouse_id: this.tmpWarehouse
      }).then(res => {
        this.tmpGoods = res.data
      })
    },
    handleChoose(row) {
      this.tmpGoodsRow = row
      this.resetTmp()
      if (row.checkedWarehouse) {
        this.tmpWarehouse = row.checkedWarehouse
        this.tmpGoods = row.stocks
      }
      this.dialogVisible = true
    },
    handleSubStock() {
      if (this.resetNum > 0) {
        this.$message({
          message: '还未分配完商品',
          type: 'warning'
        })
        return
      } else if (this.resetNum < 0) {
        this.$message({
          message: '分配的数量超过可分配数量',
          type: 'warning'
        })
        return
      }
      for (let i = 0; i < this.products.length; i++) {
        if (this.products[i].id === this.tmpGoodsRow.id) {
          this.products[i].stocks = this.tmpGoods
          this.products[i].checkedWarehouse = this.tmpWarehouse
        }
      }
      this.dialogVisible = false
    },
    doChange() {
      if (this.checkedGoods.length === 0) {
        this.$message({
          message: '请选择需要出库的商品！',
          type: 'warning'
        })
        return
      }
      for (var i = 0; i < this.checkedGoods.length; i++) {
        if (this.checkedGoods[i].stocks.length === 0) {
          this.$message({
            message: '请为商品选择出库库区',
            type: 'warning'
          })
          return
        }
      }
      stockOut({ outNos: this.ids, goods: this.checkedGoods }).then(res => {
        this.$message({
          message: '出库成功！',
          type: 'success'
        })
        this.$router.push({
          path: '/outstorage_action/picking'
        })
      })
    },
    isSelectable(row) {
      return row.total !== row.outTotal
    }
  }
}
</script>
<style lang="less">
.grid-container {
  height: auto;
  overflow: hidden;
  .detail-content {
    position: relative;
    height: auto;
    overflow: hidden;
    padding: 22px 15px;
    background: #fff;
    .detail-item {
      height: auto;
      overflow: hidden;
      line-height: 30px;
      font-size: 14px;
      padding-left: 30px;
      > span {
        display: inline-block;
        width: 150px;
        float: left;
        color: #333;
      }
      > div {
        margin-left: 160px;
        color: #999;
      }
    }
    .btn-box {
      position: absolute;
      top: 25px;
      right: 15px;
      z-index: 10;
    }
  }
  .action-column {
    text-align: right;
  }
  .color-gred {
    color: #999;
  }
}
.table-form-item {
  position: relative;
  height: 100%;
  width: 100%;
  .error-text {
    font-size: 12px;
    color: #f97042;
  }
}
.warehouse-select {
  margin-right: 20px;
  margin-bottom: 20px;
}
</style>